package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.ThreadLocalUtil;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.BusinessException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            throw  new BusinessException("非法参数");
        }
        Employee employee = employeeMapper.findByUsername(username);

        if(employee == null){
            throw new BusinessException("用户名不存在");
        }

        String md5 = SecureUtil.md5(password);
        if(!StrUtil.equals(md5,employee.getPassword())){
            throw new BusinessException("密码错误");
        }
        if(employee.getStatus()== StatusConstant.DISABLE){
            throw  new BusinessException("此账号已被禁用,请联系管理员");
        }
        Map<String,Object> map =new HashMap<>();
        map.put(JwtClaimsConstant.EMP_ID,employee.getId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecret(), jwtProperties.getAdminTtl(), map);
        EmployeeLoginVO employeeLoginVO =EmployeeLoginVO.builder().
                id(employee.getId()).
                name(employee.getName()).
                token(token).
                userName(employee.getUsername()).
                build();
        return employeeLoginVO;
    }

    @Override
    public PageResult findByPage(EmployeePageQueryDTO employeePageQueryDTO) {
        int page = employeePageQueryDTO.getPage();
        int pageSize = employeePageQueryDTO.getPageSize();
        if(page==0){
            page=1;
        }
        if(pageSize==0){
            pageSize=10;
        }
        String name = employeePageQueryDTO.getName();

        PageHelper.startPage(page,pageSize);

        List<Employee> employees = employeeMapper.findByPage(name);
        PageInfo<Employee> pageInfo = PageInfo.of(employees);

        long total = pageInfo.getTotal();
        return new PageResult(total,employees);
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        String idNumber = employeeDTO.getIdNumber();
        String phone = employeeDTO.getPhone();
        String username = employeeDTO.getUsername();
        String name = employeeDTO.getName();
        if(phone.matches("(1[3-9]\\d{9})|(0\\d{2,7}-?[1-9]\\d{4,19})")==false){
            throw new BusinessException("请输入正确的手机号");
        }
        if (!idNumber.matches("^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$")) {
            throw new BusinessException("请输入正确的身份证号");
        }
        if((username.matches("[0-9A-Za-z]{3,20}"))==false){
            throw new BusinessException("账号输入不符，请输入3-20个字符");
        }
        if((name.matches("[\\u4e00-\\u9fa5a-zA-Z]{1,12}"))==false || StrUtil.isBlank(name)){
            throw  new BusinessException("非法名称");
        }
        Employee employee = employeeMapper.findByUsername(username);
        if(employee != null && employee.getId()!=employeeDTO.getId()){
            throw new BusinessException("用户名已存在");
        }
        employee = employeeMapper.findByIdNumber(idNumber);
        if(employee != null && employee.getId()!=employeeDTO.getId()){
            throw new BusinessException("身份证已注册");
        }
        employee =employeeMapper.findByPhone(phone);
        if(employee != null && employee.getId()!=employeeDTO.getId()){
            throw new BusinessException("手机号已注册");
        }
        employee=new Employee();
        BeanUtil.copyProperties(employeeDTO,employee);
        employee.setStatus(StatusConstant.ENABLE);
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(employee.getCreateTime());
        employee.setPassword(SecureUtil.md5(PasswordConstant.DEFAULT_PASSWORD));
        //employee.setCreateUser(ThreadLocalUtil.getCurrentId());
        //employee.setUpdateUser(ThreadLocalUtil.getCurrentId());
        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
    if(id ==0 ){
        throw  new BusinessException("请填入正确ID");
    }
    Employee employee = employeeMapper.findById(id);
    return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        String idNumber = employeeDTO.getIdNumber();
        String phone = employeeDTO.getPhone();
        String username = employeeDTO.getUsername();
        String name = employeeDTO.getName();
        if(phone.matches("(1[3-9]\\d{9})|(0\\d{2,7}-?[1-9]\\d{4,19})")==false){
            throw new BusinessException("请输入正确的手机号");
        }
        if (!idNumber.matches("^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$")) {
            throw new BusinessException("请输入正确的身份证号");
        }
        if((username.matches("[0-9A-Za-z]{3,20}"))==false){
            throw new BusinessException("账号输入不符，请输入3-20个字符");
        }
        if((name.matches("[\\u4e00-\\u9fa5a-zA-Z]{1,12}"))==false || StrUtil.isBlank(name)){
            throw  new BusinessException("非法名称");
        }
        Employee employee = employeeMapper.findByUsername(username);
        if(employee != null && employee.getId()!=employeeDTO.getId()){
            throw new BusinessException("用户名已存在");
        }
        employee = employeeMapper.findByIdNumber(idNumber);
        if(employee != null&& employee.getId()!=employeeDTO.getId()){
            throw new BusinessException("身份证已注册");
        }
        employee =employeeMapper.findByPhone(phone);
        if(employee != null && employee.getId()!=employeeDTO.getId()){
            throw new BusinessException("手机号已注册");
        }
        employee=new Employee();
        BeanUtil.copyProperties(employeeDTO,employee);
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(ThreadLocalUtil.getCurrentId());
        employeeMapper.update(employee);
    }

    @Override
    public void updateStatus(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                //.updateTime(LocalDateTime.now())
                //.updateUser(ThreadLocalUtil.getCurrentId())
                .build();
        employeeMapper.update(employee);
    }
}
